package com.shr.lease.web.app.custom.converter;

import com.shr.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author Haoran Sun
 * @since 2024/06/27
 */

@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return source ->
            Arrays.stream(targetType.getEnumConstants())
                    .filter(enumConstant -> enumConstant.getCode()
                            .toString()
                            .equals(source))
                    .findFirst()
                    .orElse(null);
    }
}
